﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Auth.Application.Dtos;
using Auth.Domain.TableEntity;
using Auth.SqlSugar;
using Auth.SqlSugar.Attribute;
using Auth.SqlSugar.IocManager;
using Auth.Utility;
using Auth.Web.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Configuration;
using SqlSugar;

namespace Auth.Web.Controllers
{
    public class AuthControllerBase : Controller
    {
       
        public AuthControllerBase()
        {
        }

        #region  按钮权限

        public IActionResult PowerIndex()
        {

            return PartialView();
        }

        #endregion

        #region 获取表头

        public List<LayuiColsModel> GetTableCols<T>()
        {
            List<LayuiColsModel> colsList = new List<LayuiColsModel>();
            Type objType = typeof(T);
            //取属性上的自定义特性
            foreach (PropertyInfo propInfo in objType.GetProperties())
            {
                string name = propInfo.Name.Substring(0, 1).ToLower() + propInfo.Name.Substring(1);
                object[] objAttrs = propInfo.GetCustomAttributes(typeof(DataTableAttribute), true);
                if (objAttrs.Length > 0)
                {
                    DataTableAttribute attr = objAttrs[0] as DataTableAttribute;
                    if (attr != null)
                    {
                        if (!attr.Ignore)
                        {
                            attr.Field = name;
                            var colsModel = AutoMapper.Mapper.Map<LayuiColsModel>(attr);
                            colsList.Add(colsModel);
                        }
                    }
                }
            }

            return colsList;
        }

        #endregion

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            byte[] result;
            filterContext.HttpContext.Session.TryGetValue("CurrentUser", out result);
            if (result == null)
            {
                filterContext.Result = new RedirectResult("/Login/Index");
                return;
            }

            base.OnActionExecuting(filterContext);
        }

        /// <summary>
        /// Action 执行之后 发生
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            this.PowerLogic(filterContext);
            base.OnActionExecuted(filterContext);
        }

        /// <summary>
        /// 权限逻辑
        /// </summary>
        /// <param name="context"></param>
        private void PowerLogic(ActionExecutedContext context)
        {
            using (SqlSugarClient dbClient = DbInstance.GetInstance())
            {
                List<MenuDto> list = new List<MenuDto>();
                //判断是否为 ajax 请求
                var IsAjaxRequest = context.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";

                var userId = context.HttpContext.Session.GetString("CurrentUserId");
                var _RouteValues = context.ActionDescriptor.RouteValues;
                var _Controller = _RouteValues["controller"];
                var _Action = _RouteValues["action"];
                var _Url = $"/{_Controller}/{_Action}";

                if (!IsAjaxRequest)
                {
                    var menuIds = dbClient.Queryable<menus>().Where(s => s.Url == _Url).WithCacheIF(RedisCache.UseCache).Select(s => s.Id).ToList();
                    if (menuIds.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(userId) && Guid.Parse(userId) != Guid.Empty)
                        {
                            var roleId = dbClient.Queryable<userroles>().WithCacheIF(RedisCache.UseCache).Where(s => s.UserId == userId)
                                .Select(s => s.RoleId)
                                .ToList();
                            foreach (var item in roleId)
                            {
                                var buttonList = dbClient.Queryable<rolemenus, menus>((r, m) => new object[] {
                                    JoinType.Left,r.MenuId==m.Id}).WithCacheIF(RedisCache.UseCache)
                                    .Where((r, m) => r.RoleId == item)
                                    .Select((r, m) => new menus
                                    {
                                        Id = m.Id,
                                        Code = m.Code,
                                        Icon = m.Icon,
                                        Name = m.Name,
                                        No = m.No,
                                        ParentId = m.ParentId,
                                        Remarks = m.Remarks,
                                        SerialNumber = m.SerialNumber,
                                        Type = m.Type
                                    })
                                    .Where(m => menuIds.Contains(m.ParentId) && m.Type != 0)
                                    .OrderBy(m => m.SerialNumber).ToList();
                                list.AddRange(AutoMapper.Mapper.Map<List<MenuDto>>(buttonList));
                            }
                        }
                        else
                        {
                            var buttonList = dbClient.Queryable<menus>().WithCacheIF(RedisCache.UseCache).Where(s => menuIds.Contains(s.ParentId) && s.Type != 0).OrderBy(s => s.SerialNumber)
                                .ToList();
                            list.AddRange(AutoMapper.Mapper.Map<List<MenuDto>>(buttonList));
                        }
                        ViewData["ToolBarModel"] = list.Where(s => s.Type == 1).Distinct().ToList();
                        ViewData["ToolModel"] = list.Where(s => s.Type == 2).Distinct().ToList();
                    }
                }
                else
                {
                    //当前ajax请求的地址
                    var menu = dbClient.Queryable<menus>().WithCacheIF(RedisCache.UseCache).Where(s => _Url.Contains(s.Url)).First() ;
                    if (menu != null)
                    {
                        if (!string.IsNullOrEmpty(userId) && Guid.Parse(userId) != Guid.Empty)
                        {
                            //当前用户的角色
                            var roleId = dbClient.Queryable<userroles>().WithCacheIF(RedisCache.UseCache).Where(s => s.UserId == userId)
                                .Select(s => s.RoleId)
                                .ToList();
                            if (!dbClient.Queryable<rolemenus>().Any(s => roleId.Contains(s.RoleId)&&s.MenuId==menu.Id))
                            {
                                throw new MessageBox("请向管理员确认您此操作的权限！");
                            }
                        }
                    }

                }
            }
        }

        /// <summary>
        /// 获取服务端验证的第一条错误信息
        /// </summary>
        /// <returns></returns>
        public string GetModelStateError()
        {
            foreach (var item in ModelState.Values)
            {
                if (item.Errors.Count > 0)
                {
                    return item.Errors[0].ErrorMessage;
                }
            }

            return "";
        }

    }
}